<template>
  <div class="app-container">
    <div class="customContainer">
      <!-- 列表 -->
      <div
        style="height:32px;margin-bottom:10px;display:flex;justify-content:space-between;align-items:center"
      >
        <div>
          <span>调拨单号：</span>
          <span>{{order_no}}</span>
        </div>
        <el-button
          v-show="isShowAddGift"
          type="primary"
          size="small"
          class="pull-right"
          @click="addClick()"
        >添加礼品</el-button>
      </div>
      <el-table highlight-current-row :data="list" v-loading.body="listLoading" border size="small">
        <el-table-column align="center" label="序号" width="50">
          <template slot-scope="scope">
            <span class="indexColor">{{scope.$index+1}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="图片" prop="creat_time" width="80">
          <template slot-scope="scope">
            <div v-viewer="options" class="images fit">
              <img
                :src="scope.row.thumb"
                :data-source="scope.row.img"
                class="image"
                :key="scope.row.img"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="名称" prop="gift_name">
          <!-- <template slot-scope="scope">
            <el-button type="text" @click="showInfo(scope.row.gift_id)">{{scope.row.gift_name}}</el-button>
          </template>-->
        </el-table-column>
        <el-table-column align="center" label="礼品编号" prop="gift_id"></el-table-column>
        <el-table-column align="center" label="成本价(元)" prop="money_cost"></el-table-column>
        <el-table-column align="center" label="可调库存(个)" key="remain_num">
          <template
            slot-scope="scope"
          >{{scope.row.remain_num-scope.row.order_num+(scope.row.before_num?scope.row.before_num*1:0)}}</template>
        </el-table-column>
        <el-table-column align="center" label="调拨数量(个)" prop="order_num">
          <template slot-scope="scope">
            <el-input
              v-if="scope.row.isSave"
              :maxlength="6"
              @blur="inputBurl(scope.row)"
              v-model="scope.row.order_num"
              placeholder="请输入数量"
            ></el-input>
            <span v-else>{{scope.row.order_num}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实收数量(个)" prop="arrive_num"></el-table-column>
        <el-table-column align="center" label="调拨金额(元)" prop="total">
          <template slot-scope="scope">{{scope.row.money_cost*scope.row.order_num|keepTwoNum}}</template>
        </el-table-column>
        <el-table-column align="center" label="实收金额(元)" prop="arrive_money"></el-table-column>
        <el-table-column align="center" label="操作" v-if="isShowAddGift" key="setGift">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="delClick(scope.$index)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 弹框 -->
    <el-dialog width="400px" title="添加礼品" :visible.sync="addDialog">
      <div class="info_dialog">
        <div>名称：{{gift_info.gift_name}}</div>
        <div>礼品编号：{{gift_info.id}}</div>
        <div>神采编号：{{gift_info.no_obsolete}}</div>
        <div>国标码：{{gift_info.gb_code}}</div>
        <div>一级类别：{{gift_info.type_name_one}}</div>
        <div>二级类别：{{gift_info.type_name_second}}</div>
        <div>三级类别：{{gift_info.type_name}}</div>
        <div>材质：{{gift_info.texture}}</div>
        <div>产品尺寸：{{gift_info.product_size}}</div>
        <div>包装尺寸：{{gift_info.packing_size}}</div>
      </div>
    </el-dialog>
    <!-- 新增弹框 -->
    <el-dialog width="400px" title="添加礼品" :visible.sync="addDialog" @close="callOf">
      <div>
        <el-input
          style="width:290px;margin-right:10px"
          size="small"
          v-model="addData.gift_id"
          placeholder="请输入完整的礼品编号"
        ></el-input>
        <dj-button size="small" @search="searchClick">
          <template #default>搜索</template>
        </dj-button>
      </div>
      <div class="gift_info">
        <div class="gift_img">
          <img height="70px" :src="add_gift_info.thumb" />
        </div>
        <div class="info_dialog add">
          <div>名称：{{add_gift_info.name}}</div>
          <div>成本价：{{add_gift_info.money_sell}}</div>
          <div>礼品编号：{{add_gift_info.gift_id}}</div>
          <div>神采编号：{{add_gift_info.no_obsolete}}</div>
          <div>国标码：{{add_gift_info.gb_code}}</div>
          <div>一级类别：{{add_gift_info.type_name_one}}</div>
          <div>二级类别：{{add_gift_info.type_name_second}}</div>
          <div>三级类别：{{add_gift_info.type_name}}</div>
          <div>材质：{{add_gift_info.texture}}</div>
          <div>产品尺寸：{{add_gift_info.product_size}}</div>
          <div>包装尺寸：{{add_gift_info.packing_size}}</div>
          <div>
            可调库存：
            <span v-show="add_gift_info.num">{{add_gift_info.num - gift_num}}</span>
          </div>
        </div>
        <div class="gift_num">
          <div class="num_tag">数量</div>
          <el-input-number
            size="small"
            v-model="gift_num"
            :min="1"
            :max="add_gift_info.num*1>999999?999999:add_gift_info.num*1"
            :step="add_gift_info.box_num*1>0?add_gift_info.box_num*1:1"
          ></el-input-number>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button
            :disabled="!add_gift_info.gift_id"
            type="primary"
            size="mini"
            @click="addClick(1)"
          >添加</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 提交订单弹出窗口 -->

    <el-dialog :visible.sync="isShowAddCart" width="1000px" title="收货信息">
      <el-row>
        <el-col>
          <div class="row-block">
            <span style="text-align:right;font-size:14px;margin-left:28px">收货店：</span>
            <el-select
              disabled
              @change="getStoreInfo"
              size="small"
              placeholder="请选择门店"
              v-model="sInfo.store_id"
              filterable
              style="width:300px"
            >
              <el-option
                v-for="item in store_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="7">
          <div class="row-block">
            <span style="width:30%;text-align:right;font-size:14px">收货人：</span>
            <el-input
              disabled
              size="small"
              style="width:70%;font-size:14px"
              placeholder="请输入姓名"
              v-model="sInfo.name"
            ></el-input>
          </div>
        </el-col>
        <el-col :span="7">
          <div class="row-block">
            <span style="width:30%;text-align:right;font-size:14px">电话：</span>
            <el-input
              disabled
              size="small"
              style="width:70%;"
              placeholder="请输入手机号码"
              v-model="sInfo.phone"
            ></el-input>
          </div>
        </el-col>
        <el-col :span="10">
          <div class="row-block">
            <div style="width:30%;height:50%;">
              <div style="width:388px;height:50%;display:flex;margin-left:22px;">
                <!-- 地区 -->
                <span
                  style="font-size:14px;text-align:right;display:inline-block;width:75px;line-height:29px;padding-right:2px"
                >地区：</span>
                <el-form :inline="true" class="demo-form-inline" size="small">
                  <el-form-item>
                    <keep-alive>
                      <dj-region
                        v-if="isShowAddCart"
                        :updateData="reg"
                        :getName="true"
                        :isClear="clearRegion"
                        :disabled="true"
                        @provVal="provVal(arguments)"
                        @cityVal="cityVal(arguments)"
                        @areaVal="areaVal(arguments)"
                        ref="region"
                      ></dj-region>
                    </keep-alive>
                  </el-form-item>
                </el-form>
              </div>
            </div>
            <!-- <span style="width:30%;text-align:right;font-size:14px">地区：</span>
            <div style="width:70%;">
              <keep-alive>
                <dj-region v-if="isShowAddCart" :prov="reg.prov" :city="reg.city" :area="reg.area" :getName="true" @provVal="provVal(arguments)"
           @cityVal="cityVal(arguments)" @areaVal="areaVal(arguments)" ref="region"></dj-region>
              </keep-alive>
            </div>-->
          </div>
        </el-col>
      </el-row>
      <div class="row-block-full">
        <span style="width:8.75%;text-align:right;font-size:14px">详细地址：</span>
        <el-input
          disabled
          style="width:91.25%;font-size:14px"
          type="textarea"
          :rows="2"
          :maxlength="160"
          placeholder="请输入详细地址"
          resize="none"
          v-model="sInfo.address"
        ></el-input>
      </div>
      <div class="row-block-full">
        <div style="width:8.75%;text-align:right;font-size:14px">订单信息：</div>
        <p
          style="width:91.25%;text-align:center;font-size:16px"
        >种类合计：{{list.length}}种 数量合计：{{allNum}}个 金额合计(不含运费)：{{allTotal|keepTwoNum}}元</p>
      </div>
      <div class="row-block-full">
        <span style="width:8.75%;text-align:right;font-size:14px">订单备注：</span>
        <div style="width:91.25%;font-size:14px">
          <el-input
            style="display:inline-block;width:100%;"
            type="textarea"
            :rows="4"
            placeholder="备注"
            v-model="sInfo.remark"
            resize="none"
            :maxlength="160"
          ></el-input>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowAddCart = false">上一步</el-button>
        <el-button type="primary" @click="saveClick()">保存</el-button>
      </div>
    </el-dialog>
    <!-- 自定义底部 -->
    <div class="bottom_box">
      <el-button
        class="pull-right"
        size="small"
        type="primary"
        @click="receiving()"
        v-show="!isShowAddGift&&!isLook"
      >修改</el-button>
      <!-- :loading="btnLoding" -->
      <div v-show="isShowAddGift&&!isLook" class="pull-right">
        <el-button @click="cancel" type="primary" size="small">取消</el-button>
        <el-button @click="nextStep" type="primary" size="small">下一步</el-button>
      </div>
      <div class="pull-right total">
        <span>种类合计：{{list?list.length:0}}种</span>
        <span>当前数量合计：{{allNum}}个</span>
        <span>当前金额合计(不包含运费)：{{allTotal}}元</span>
      </div>
    </div>
  </div>
</template> 
<script>
import {
  getList,
  getInfo,
  getStore,
  getGift,
  edit,
  storeInfo,
} from "@/api/warehouse/loDetail";
import { positiveInt } from "@/utils/validate";
export default {
  data() {
    return {
      addDialog: false,
      isLook: false,
      isFirst: false,
      clearRegion: false,
      house: "",
      oldData: {}, //未修改的数据
      sInfo: {},
      add_gift_info: {},
      reg: {
        prov: "",
        city: "",
        area: "",
      },
      store_list: [],
      listLoading: false,
      list: [],
      delData: [],
      type: "",
      order_no: "",
      id: "",
      options: {
        //预览图配置
        toolbar: true,
        url: "data-source",
      },
      gift_info: {},
      gift_num: 1,
      isShowAddGift: false,
      addData: {
        gift_id: "",
        store_id: "",
      },
      info: {},
      isShowAddCart: false, //收货信息弹窗
      saveForm: {
        order: [], //购买了哪些商品
        order_id: "", //订单的id
        prov: "",
        city: "",
        dist: "",
        phone: "",
        name: "",
        address: "",
        remark: "",
      },
      route: { name: "warehouse/loDetail" },
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      //当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
      if (vm.$route.params.routerflag) {
        vm.order_no = vm.$route.params.order_no;
        vm.saveForm.order_id = vm.$route.params.id;
        vm.sInfo = vm.$route.params.sInfo;
        vm.saveForm.prov = vm.sInfo.prov;
        vm.saveForm.city = vm.sInfo.city;
        vm.saveForm.dist = vm.sInfo.dist;
        vm.saveForm.prov_name = vm.sInfo.prov_name;
        vm.saveForm.city_name = vm.sInfo.city_name;
        vm.saveForm.dist_name = vm.sInfo.dist_name;
        vm.saveForm.house_id_out = vm.sInfo.house_id_out;
        vm.addData.store_id = vm.sInfo.store_id_out;
        vm.isLook = vm.$route.params.isLook;
        vm.isShowAddGift = false;
        vm.isFirst = true;
        vm.fatchData();
        vm.getStoreList();
        // vm.getInfo(vm.$route.params.info);
      }
    });
  },
  methods: {
    getStoreList() {
      getStore({ look_del: 0, category_id: 172 }).then((res) => {
        this.store_list = res;
      });
    },
    //获取门店信息
    getStoreInfo(id) {
      storeInfo({ store_id: id }).then((res) => {
        this.sInfo.name = res.linkman;
        this.sInfo.phone = res.phone;
        this.sInfo.address = res.address;
        this.saveForm.prov = res.prov_id;
        this.saveForm.prov_name = res.prov_name;
        this.saveForm.city = res.city_id;
        this.saveForm.city_name = res.city_name;
        this.saveForm.dist = res.dist_id;
        this.saveForm.dist_name = res.dist_name;
        this.reg = {
          prov: res.prov_id,
          city: res.city_id,
          area: res.dist_id,
        };
      });
    },
    //搜索
    searchClick() {
      this.add_gift_info = {};
      this.gift_num = 1;
      if (!this.addData.gift_id) {
        this.$message.error("请输入完整的礼品编号");
        return;
      }
      getGift(this.addData).then((res) => {
        if (res.length != 0) {
          let data = res[0];
          data.texture = data.texture == "null" ? "" : data.texture;
          data.money_sell = (data.money_sell * 1).toFixed(2);
          this.add_gift_info = data;
          this.gift_num =
            data.num * 1 < data.box_num * 1
              ? data.num
              : data.box_num * 1 > 0
              ? data.box_num
              : 1;
        } else {
          this.$message.error("未搜索到该礼品");
        }
      });
    },
    inputBurl(row) {
      if (!positiveInt(row.order_num)) {
        row.order_num = 1;
      } else if (
        row.order_num >
        row.remain_num * 1 + (row.before_num ? row.before_num * 1 : 0)
      ) {
        row.order_num =
          row.remain_num * 1 + (row.before_num ? row.before_num * 1 : 0);
      }
    },
    getData(data) {
      data.forEach((val) => {
        val.look_money = val.money_cost;
        val.money_cost = (val.money_cost / 1).toFixed(2);
        val.arrive_money = (val.arrive_num * val.money_cost).toFixed(2);
        val.before_num = val.order_num;
        val.type = 0;
        val.isSave = false;
      });
      this.oldData = JSON.parse(JSON.stringify(data));
      this.list = data;
    },
    fatchData() {
      this.listLoading = true;
      this.list = [];
      getList({ id: this.saveForm.order_id })
        .then((res) => {
          this.getData(res.message);
          this.listLoading = false;
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    receiving() {
      //修改
      this.isShowAddGift = true;
      this.list.forEach((val) => {
        val.isSave = true;
      });
    },
    cancel() {
      this.isShowAddGift = false;
      this.list = JSON.parse(JSON.stringify(this.oldData));
    },
    nextStep() {
      if (this.list.length == 0) {
        this.$message.error("请选择礼品!");
        return;
      }
      let isPass = true;
      this.list.forEach((val) => {
        if (!positiveInt(val.order_num)) {
          this.$message.error("礼品数量只能为正整数");
          isPass = false;
          return;
        } else if (
          this.type == 2 &&
          val.order_num * 1 >
            val.remain_num * 1 + (val.before_num ? val.before_num * 1 : 0)
        ) {
          this.$message.error("礼品数量不能大于可调数量");
          isPass = false;
          return;
        }
      });
      if (!isPass) {
        return;
      }
      this.isShowAddCart = true;
      if (this.isFirst) {
        setTimeout(() => {
          this.reg = {
            prov: this.saveForm.prov,
            city: this.saveForm.city,
            area: this.saveForm.dist,
          };
        }, 0);
        this.isFirst = false;
      }
    },
    save(type) {
      let data = [];
      let newData = this.list.filter((val) => val.type == 1);
      newData.forEach((val) => {
        data.push({
          gift_id: val.gift_id,
          order_num: val.order_num,
          look_money: val.money_cost * 1000000,
          money_cost: val.money_cost * 1000000,
          type: 1,
        });
      });
      this.delData.forEach((val) => {
        data.push({
          gift_id: val.gift_id,
          order_num: val.order_num,
          look_money: val.look_money,
          money_cost: val.money_cost,
          type: 2,
          mapping_id: val.mapping_id,
        });
      });
      let lastData = this.list.filter((val) => val.type == 0);
      lastData.forEach((val) => {
        let gift = this.oldData.find((item) => item.gift_id == val.gift_id);
        if (gift.order_num != val.order_num) {
          data.push({
            gift_id: val.gift_id,
            order_num: val.order_num,
            look_money: val.look_money * 1000000,
            money_cost: val.money_cost * 1000000,
            type: 3,
            mapping_id: val.mapping_id,
            before_num: gift.before_num,
          });
        }
      });
      this.saveForm.order = data;
      this.saveForm.status_type = 0;
      this.saveForm.store_id_in = this.sInfo.store_id;
      this.saveForm.name = this.sInfo.name;
      this.saveForm.phone = this.sInfo.phone;
      this.saveForm.address = this.sInfo.address;
      this.saveForm.remark = this.sInfo.remark;
      edit(this.saveForm).then((res) => {
        if (res.code == 1) {
          this.$message.success(res.message);
          this.oldData = [];
          this.delData = [];
          this.isShowAddCart = false;
          this.$store.dispatch("delVisitedViews", this.route).then(() => {
            this.$router.push({
              name: "warehouse/loInfo",
              params: { isUpdate: 1 },
            });
          });
        }
      });
    },
    saveClick() {
      if (!this.sInfo.name) {
        this.$message.error("收货人不能为空!");
        return;
      }
      if (!this.sInfo.phone) {
        this.$message.error("手机号不能为空!");
        return;
      }

      if (!this.reg.prov || !this.reg.city) {
        this.$message.error("请选择详细地址!");
        return;
      }
      let nameReg = /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/; //验证姓名正则
      if (!nameReg.test(this.sInfo.name)) {
        this.$message.error("输入名字不规范");
        return;
      }
      let phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.sInfo.phone)) {
        this.$message.error("电话号码格式不正确");
        return;
      }
      this.save();
    },
    // 子组件传过来的省
    provVal(val) {
      this.saveForm.prov = val[0];
      this.saveForm.prov_name = val[1];
    },
    // 子组件传过来的市
    cityVal(val) {
      this.saveForm.city = val[0];
      this.saveForm.city_name = val[1];
    },
    // 子组件传过来的区
    areaVal(val) {
      this.saveForm.dist = val[0];
      this.saveForm.dist_name = val[1];
    },
    //移除
    delClick(index) {
      this.$confirm("确定移除？移除后数据不可恢复！", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let delGift = this.list.splice(index, 1)[0];
        if (delGift.type == 0) {
          this.delData.push(delGift);
        }
      });
    },
    //添加
    addClick(type) {
      if (type) {
        let index = this.list.findIndex(
          (val) => val.gift_id == this.add_gift_info.gift_id
        );
        if (index >= 0) {
          this.list[index].order_num =
            this.list[index].order_num * 1 + this.gift_num * 1;
          this.list[index].remain_num = this.add_gift_info.num;
          this.list[index].money_cost = this.add_gift_info.money_sell;
        } else {
          this.list.unshift({
            type,
            gift_id: this.add_gift_info.gift_id,
            money_cost: this.add_gift_info.money_sell,
            order_num: this.gift_num,
            img: this.add_gift_info.img,
            thumb: this.add_gift_info.thumb,
            isSave: true,
            gift_name: this.add_gift_info.name,
            remain_num: this.add_gift_info.num,
            arrive_num: 0,
            arrive_money: "0.00",
          });
        }
        this.addDialog = false;
      } else {
        this.addDialog = true;
      }
    },
    callOf() {
      this.add_gift_info = {};
      this.gift_num = 1;
      this.addData.gift_id = "";
    },
  },
  computed: {
    allNum: function () {
      if (this.list.length <= 0) {
        return 0;
      }
      let num = 0;
      this.list.forEach((val) => {
        num = num + val.order_num * 1;
      });
      return num;
    },
    allTotal: function () {
      if (this.list.length <= 0) {
        return 0;
      }
      let total = 0;
      this.list.forEach((val) => {
        total = total + val.order_num * val.money_cost;
      });
      return total.toFixed(2);
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.order_info,
.rece_info {
  margin-bottom: 14px;
  .info_item {
    display: inline-block;
    width: 300px;
    margin-bottom: 10px;
  }
}
.order_title {
  margin-bottom: 10px;
}
.info_dialog {
  div + div {
    margin-top: 10px;
  }
}
.dialog-footer {
  text-align: right;
}
.info_dialog {
  div + div {
    margin-top: 10px;
  }
}
.gift_num {
  display: flex;
  margin-top: 10px;
  align-items: center;
  .num_tag {
    margin-right: 80px;
  }
}
.gift_img {
  height: 90px;
  text-align: center;
  padding: 10px;
}
.bottom_box {
  .total {
    margin: 8px;
    span {
      margin-right: 20px;
    }
  }
}
</style>
<style scoped>
.app-container >>> .mycard.el-input > input {
  height: 28px;
}
.mycard .el-input-number span {
  line-height: 28px;
}
.app-container >>> .el-dialog .myStorehouse input {
  width: 269px;
}
.app-container >>> .el-dialog div.phoneInput {
  display: inline-block;
  width: 10px;
}
.app-container >>> .el-dialog div.phoneInput > input {
  width: 199px !important;
  height: 32px !important;
}
/* .app-container
  >>> .el-dialog
  .el-dialog__body
  .myArea
  form
  div.el-form-item__content
  > div {
  width: 300px;
}
.app-container >>> .el-dialog .el-dialog__body .myArea > div {
  width: 500px;
  display: flex;
}
.app-container >>> .el-dialog .el-dialog__body .myArea form > div {
  margin-left: 0;
} */
.app-container >>> .el-dialog textarea {
  border-radius: unset;
  padding: 10px 15px;
}
.row-block {
  width: 100%;
  height: 50%;
  margin: 8px 0;
  display: flex;
  align-items: center;
}

.row-block-full {
  width: 100%;
  height: 100%;
  margin-top: 8px;
  display: flex;
  align-items: center;
}
</style>
